package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import pojo.User;
import service.UserManager;
import service.factory.ManagerFactory;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final static Logger logger = LogManager.getLogger(LoginServlet.class);
	private UserManager manager;
       
    public LoginServlet() {
        super();
       manager = ManagerFactory.getUserManagerInstance();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("uname");
		String psd = request.getParameter("psd");
		request.setAttribute("uname", uname);
		request.setAttribute("psd", psd);
		boolean isError = true;
		if (uname==null||"".equals(uname)) {
			request.setAttribute("euname", "username can not be empty");
			isError = false;
		}
		if (psd==null||"".equals(psd)) {
			request.setAttribute("epsd", "password can not be null");
			isError =false;
		}
		if (!isError) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		User user = manager.findByName(uname);
		if (user==null) {
			request.setAttribute("euname", "user not exist");
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}else{
			if (!user.getPsd().equals(psd)) {
				request.setAttribute("epsd", "wrong password ");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			logger.info(user.getUname()+":is login");
			response.sendRedirect("list");
		
		}
	}

}
